package com.qianniu.napi.common.shiro;

import com.qianniu.napi.admin.web.AuthController;
import com.qianniu.napi.common.util.IdentifyingCode;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

public class MyFormAuthenticationFilter extends FormAuthenticationFilter {

    private static Logger logger = LoggerFactory.getLogger(MyFormAuthenticationFilter.class);

//    表单提交时，先验证验证码，如果验证成功再走登录流程
//    用于验证码验证的 Shiro 拦截器在用于身份认证的拦截器之前运行；但是如果验证码验证拦截器失败了，就不需要进行身份认证拦截器流程了；
//    所以需要修改下如FormAuthenticationFilter 身份认证拦截器，当验证码验证失败时不再走身份认证拦截器。
//    @Override
//    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
//        logger.debug(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>onAccessDenied");
//        // 在这里进行验证码的校验
//        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
//        HttpSession session = httpServletRequest.getSession();
//        // 取出验证码
//        String validateCode = (String) session.getAttribute(IdentifyingCode.VERIFY_CODE_KEY);
//        // 取出页面的验证码
//        // 输入的验证和session中的验证进行对比
//        String randomcode = httpServletRequest.getParameter("captcha");
//        logger.debug(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>randomcode="+randomcode);
//        if (randomcode == null || validateCode == null || !randomcode.equals(validateCode)) {
//            // 如果校验失败，将验证码错误失败信息，通过DEFAULT_ERROR_KEY_ATTRIBUTE_NAME=shiroLoginFailure设置到request中
//            // FormAuthenticationFilter会统一将登录（subject.login（））后的异常全部转换放在这个request中，具体方法如下：etFailureAttribute(ServletRequest
//            // request, AuthenticationException ae)
//            httpServletRequest.setAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME,"kaptchaValidateFailed");// 自定义登录异常
//            //throw new ValidateFailedException("验证码校验失败");
//            // 拒绝访问，不再校验账号和密码
//            return true;
//        }
//        return super.onAccessDenied(request, response);
//    }

//    @Override
//    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
//        if(request.getAttribute(getFailureKeyAttribute()) != null) {
//            return true;
//        }
//        return super.onAccessDenied(request, response);
//    }

    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
        String successUrl = "/home";
        WebUtils.issueRedirect(request,response,successUrl);
        return false;
    }
}
